<?php
/**
 * 
 * @author Paolo Bertuzzo
 *
 */
namespace Catalog\Form;

use Zend\Form\Form;
use Zend\Form\Element;
use Catalog\Service\ProductService;
use Utilities\Session\SessionFacade;

/**
 */
abstract class AbstractProductForm extends Form
{

    /**
     */
    protected $productService;
    
    /**
    */
    protected $productId;
    
    /**
    */
    protected $store;
    
    /**
     */
    public function __construct($name, $options) 
    {
        parent::__construct();

        $this->productId = $options['product_id'];
        $this->productService = $options['product_service'];
        $this->store = $options['store'];

        // Set form action
        $this->setAttribute('method', 'post');
        
        // Add the price and submit elements
        $sessionFacade = new SessionFacade();
        
        $this->add(array(
            'name' => 'submit',
            'attributes' => array(
                'type' => 'submit_element',
                'product_id' => $this->productId,
                'price' => $this->getProductPrice(),
                'locale' => $sessionFacade->getLocale(),
                'attributes' => $this->getProductAttributes()
            )
        ));
    }
    
    /**
     * 
     */
    private function getProductPrice()
    {
    	$price = $this->productService->getProductPrice($this->store->getId(), $this->productId);
    	
    	return $price == null ? 0 : array('value' => $price->getValue(), 'currency' => $price->getCurrency());
    }
    
    /**
     */
    protected abstract function getProductAttributes();
    
    /**
     *
     * @param string $type
     */
    protected function getProductAttributeValues($type)
    {
    	$attributes = $this->productService->getAttributeValues($this->store->getId(), $this->productId,
    			$type, $this->store->getLanguage());
    
    	$values = array();
    	 
    	for ($i = 0; $i < count($attributes); $i += 3)
    		array_push($values, array(
    				'id' => $attributes[$i + 1]->getId(),
    				'text' => $attributes[$i]->getText(),
    				'value' => $attributes[$i + 1]->getValue(),
    				'is_default' => $attributes[$i + 1]->isDefault(),
    				'price' => $attributes[$i + 2]->getValue(),
    				'currency' => $attributes[$i + 2]->getCurrency()
    		));
    	 
    	return $values;
    }
    
    /**
     * @param string $type
     */
    protected function getProductAttribute($type)
    {
    	$attribute = $this->productService->getAttribute($this->productId,
    			$type, $this->store->getLanguage());
    
    	return array(
    			'id' => $attribute->getAttributeId(),
    			'text' => $attribute->getText()
    	);
    }
    
}

?>